﻿using System.Data;
using Microsoft.Data.SqlClient;
namespace SQLTool
{
    public class SQLOPT
    {

        private static string _connectionString = "uid=sa; pwd=Ycjc@8012;data source=.; dataBase=NetworkOPS; TrustServerCertificate=True";

     
        // 执行查询并返回DataTable
        public static DataTable ExecuteQuery(string query)
        {
            using (SqlConnection connection = new SqlConnection(_connectionString))
            {
                using (SqlCommand command = new SqlCommand(query, connection))
                {
                    connection.Open();
                    using (SqlDataReader reader = command.ExecuteReader())
                    {
                        DataTable resultTable = new DataTable();
                        resultTable.Load(reader);
                        return resultTable;
                    }
                }
            }
        }

        /// <summary>
        /// 执行更新或插入操作
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public static int ExecuteNonQuery(string query)
        {
            using (SqlConnection connection = new SqlConnection(_connectionString))
            {
                using (SqlCommand command = new SqlCommand(query, connection))
                {
                    connection.Open();
                    return command.ExecuteNonQuery();
                }
            }
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="param"></param>
        /// <returns>首行首列</returns>
        public static object ExecuteScalar(string sql, params SqlParameter[] param)
        {
            using (SqlConnection con = new SqlConnection(_connectionString))
            {
                using (SqlCommand cmd = new SqlCommand(sql, con))
                {
                    con.Open();
                    if (param != null)
                    {
                        cmd.Parameters.AddRange(param);
                    }
                    return cmd.ExecuteScalar();
                }
            }
        }
    }
}

// 使用示例：
/*
string connectionString = "Your SQL Server Connection String Here";
SQLTool tool = new SQLTool(connectionString);

// 查询
DataTable result = tool.ExecuteQuery("SELECT * FROM YourTableName");

// 插入
int rowsAffected = tool.ExecuteNonQuery("INSERT INTO YourTableName (Column1, Column2) VALUES (Value1, Value2)");

// 更新
int rowsUpdated = tool.ExecuteNonQuery("UPDATE YourTableName SET Column1 = NewValue WHERE SomeColumn = SomeValue");
*/
